/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.cloud.uaa.granter;

import com.lvyh.lightframe.cloud.uaa.service.ValidateCodeService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.TokenGranter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * TokenGranter 扩展 将自定义的grant_type类型添加到oauth2中
 * 使用方法:
 * 在configure(AuthorizationServerEndpointsConfigurer endpoints)中:
 * <p>
 * 获取自定义tokenGranter
 * TokenGranter tokenGranter = TokenGranterExt.getTokenGranter(authenticationManager, endpoints, baseRedis, userClient, socialProperties);
 * endpoints.tokenGranter(tokenGranter);
 */
public class TokenGranterExt {
    public static TokenGranter getTokenGranter(final AuthenticationManager authenticationManager, final AuthorizationServerEndpointsConfigurer endpointsConfigurer, ValidateCodeService validateCodeService) {

        //  默认tokenGranter集合 security 自带的-获取默认的授权模式
        List<TokenGranter> tokenGranters = new ArrayList<>(Collections.singletonList(endpointsConfigurer.getTokenGranter()));
        //添加验证码
        tokenGranters.add(new PwdImgCodeGranter(authenticationManager, endpointsConfigurer.getTokenServices(), endpointsConfigurer.getClientDetailsService(), endpointsConfigurer.getOAuth2RequestFactory(), validateCodeService));
        return new CompositeTokenGranter(tokenGranters);
    }
}
